package com.kfyang.manualgear.daoplugin.generator;

import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.util.IntentionFamilyName;
import com.intellij.codeInspection.util.IntentionName;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.kfyang.manualgear.daoplugin.Constants;
import org.jetbrains.annotations.NotNull;

public class GenerateMethodInfoIntention implements IntentionAction {
    private String methodName;
    private Document document;
    private PsiFile yamlFile;

    @Override
    public @IntentionName @NotNull String getText() {
        return "[manual gear] generate methodInfo";
    }

    @Override
    public @NotNull @IntentionFamilyName String getFamilyName() {
        return getText();
    }

    @Override
    public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile psiFile) {
        PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset());
        PsiClass superElement;
        if (element != null && element.getParent() instanceof PsiMethod psiMethod
           && (superElement = PsiTreeUtil.getParentOfType(element, PsiClass.class)) != null
           && superElement.isInterface() && superElement.hasAnnotation(Constants.DAO_ANNO)) {
            methodName = psiMethod.getName();
            String fileName = psiFile.getName();
            String className = fileName.substring(0, fileName.lastIndexOf('.'));
            PsiFile[] files = PsiShortNamesCache.getInstance(project).getFilesByName(className + ".yml");

            if (files.length != 1) {
                return false;
            }

            yamlFile = files[0];
            document = PsiDocumentManager.getInstance(project).getDocument(yamlFile);

            return true;
        }
        return false;
    }

    @Override
    public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException {
        YmlGenerateDialogWrapper dialogWrapper = new YmlGenerateDialogWrapper(project, methodName, document, yamlFile);

        dialogWrapper.show();
    }

    @Override
    public boolean startInWriteAction() {
        return false;
    }
}
